package edu.cug.water.crawler.job.task.cug;

import edu.cug.water.crawler.common.exception.RRException;
import edu.cug.water.crawler.job.task.ITask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;

@Component("job:HealthCheckIn")
@Slf4j
public class HealthCheckInTask implements ITask {
    @Override
    public int run(String params) {
        String[] split = params.split("&");
        String id = split[0].trim();
        String pwd = split[1].trim();
        log.info("开始执行ID：{} 的健康打卡！", id);

        String exe = "/root/anaconda3/bin/python";
        //String exe = "G:\\Anaconda3\\python.exe";
        String command = "/home/health/check-in.python";
        //String command = "C:\\Users\\Hades\\Desktop\\test.py";
        String logFilePath = "/home/log/check-in.log";

        ProcessBuilder processBuilder = new ProcessBuilder(exe, command, id, pwd);
        // 重定向输出
        File file = new File(logFilePath);
        clearFileContent(file);
        processBuilder.redirectOutput(file);

        Process process = null;
        try {
            process = processBuilder.start();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RRException("Python 程序IOException：" + e.getMessage());
        }

        try {
            int i = process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // Print output to console
        ProcessBuilder.Redirect output = processBuilder.redirectOutput();
        File outputFile = output.file();
        BufferedReader br = null;
        String result = null;
        try {
            br = new BufferedReader(new FileReader(outputFile));
            StringBuilder builder = new StringBuilder();
            while (true) {
                if (!((result = br.readLine()) != null)) break;
                builder.append(result);
            }

            result = builder.toString();
            log.info("Python程序执行结果\n {}", builder.toString());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RRException("找不到日志文件！" + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RRException("文件读取异常：" + e.getMessage());
        }

        if (result.indexOf("打卡成功") == -1) {
            throw new RRException(result);
        }
        return -1;
    }


    /**
     * 清空文件内容
     * @param file
     * @throws IOException
     */
    private void clearFileContent(File file) {
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file);
            fileWriter.write("");
            fileWriter.flush();
            fileWriter.close();
            log.info("{}原文件内容已被清空", file.getName());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RRException("清空文件内容失败！");
        }
    }

}
